<template>
  <div class="table-container">
    <div class="left">
      <el-input v-model="filterText" placeholder="输入关键字进行过滤" />

      <el-tree
        ref="orgTree"
        class="filter-tree"
        :data="deptTree"
        :props="defaultProps"
        :filter-node-method="filterNode"
        @node-click="handleDeptTreeClick"
      />
    </div>
    <div class="right">
      <search-bar
        key="users"
        v-model="queryParams"
        class="header"
        :config="searchColumn"
        @search="handleSearch"
        @searchReset="handleReset"
      />

      <el-button v-hasPermi="['system.accounts.add']" class="m_96" type="primary" @click="handleUserDialog">
        新增用户</el-button
      >

      <table-page
        width="100%"
        class="user-table"
        :table-data="tableData"
        :table-column="tableColumn"
        :is-index="false"
        :is-selection="false"
        :total="pages.total"
        :page-size="pages.pageSize"
        :current-page="pages.pageNum"
        @sizeChange="handleSizeChange"
        @currentChange="handleCurrentChange"
      />
      <!-- 新增/编辑人员 -->
      <el-dialog
        :width="userDialogWidth"
        class="app-dialog"
        :title="`${userDialogType}人员`"
        :visible.sync="userDialogVisible"
        :before-close="handleUserDialogClose"
        :close-on-click-modal="false"
      >
        <!-- Tabs 组件 -->
        <el-tabs v-model="activeTab" class="tabs" @tab-click="handleTabClick">
          <el-tab-pane class="tabs-item" label="帐号信息" name="basicInfo" />
          <el-tab-pane class="tabs-item" label="角色信息" name="authInfo" />
        </el-tabs>

        <div class="container">
          <div v-show="activeTab === 'basicInfo'">
            <Form
              v-if="deptOptions.length"
              ref="userEdit"
              v-model="userDialogData"
              :config="userDialogConfig"
              label-width="80px"
              label-position="top"
            />
          </div>
          <div v-show="activeTab === 'authInfo'" class="roleTree">
            <el-transfer
              v-model="selectValue"
              :props="{
                key: 'roleId',
                label: 'roleName'
              }"
              filterable
              :filter-method="filterRole"
              filter-placeholder="请输入标题名称"
              :data="roleOptions"
              :titles="getTransferTitles(userDialogData.belongSystem, selectValue.length)"
              :right-default-checked="selectValue"
            />
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="button" @click="handleUserDialogClose">取 消</el-button>
          <el-button class="button" type="primary" @click="handleUserSubmit">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 权限弹窗 -->
      <!-- <el-dialog
      width="40%"
      class="app-dialog"
      title="编辑权限"
      :visible.sync="authDialogVisible"
      :before-close="handleAuthDialogClose"
      :close-on-click-modal="false"
    >
      <div class="container" style="height: 450px; overflow-y: scroll" v-if="authDialogVisible">
        <el-tree
          ref="authTree"
          show-checkbox
          :data="authOptions"
          node-key="name"
          :props="{
            value: 'name',
            label: 'displayName',
            children: 'children',
          }"
          :default-expand-all="true"
          :default-checked-keys="checkedKeys"
          :check-strictly="false"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAuthDialogClose">取 消</el-button>
        <el-button type="primary" @click="handleAuthSubmit">确 定</el-button>
      </span>
    </el-dialog> -->
    </div>
  </div>
</template>

<script>
import Form from '@/components/Form'
import SearchBar from '@/components/SearchBar'
import TablePage from '@/components/TablePage'
import {
  listUser,
  addUser,
  updateUser,
  getUser,
  delUser,
  deptTreeSelect,
  deptOtherId,
  roleOptionList,
  roleBySystem
} from '@/api/SystemSetting/accounts'

export default {
  name: 'UserSearchTable',
  components: {
    SearchBar,
    TablePage,
    Form
  },
  data() {
    return {
      activeTab: 'basicInfo',
      userDialogWidth: '470px',
      filterText: '',
      roleOptions: [],
      checkedKeys: [],
      queryParams: {},
      selectValue: [],
      deptOptions: [],
      deptTree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isFetchingRoles: false,
      filterRole(query, item) {
        return item.roleName.toLowerCase().indexOf(query.toLowerCase()) > -1
      },
      searchColumn: [
        { prop: 'workNumber', type: 'input', placeholder: '账号名称' },
        { prop: 'userName', type: 'input', placeholder: '姓名' },
        { prop: 'phonenumber', type: 'input', placeholder: '手机号' },
        {
          prop: 'status',
          type: 'select',
          placeholder: '状态',
          options: [
            { label: '生效', value: '0' },
            { label: '失效', value: '1' },
            { label: '休眠', value: '2' }
          ]
        },
        {
          prop: 'belongSystem',
          type: 'select',
          placeholder: '所属系统',
          options: [
            { label: 'CRM', value: '0' },
            { label: '劳保', value: '1' }
          ]
        },
        {
          prop: 'search',
          type: 'button',
          policy: ['system.accounts.query']
        }
        // policy: ['CentralControl.PackageVersion.Update'],
      ],
      tableData: [],
      tableColumn: [
        { label: '帐号', prop: 'workNumber' },
        // { label: '用户名', prop: 'userName' },
        { label: '姓名', prop: 'userName' },
        { label: '岗位', prop: 'postName' },
        { label: '角色', prop: 'roleNames' },
        { label: '手机号', prop: 'phonenumber' },
        {
          label: '状态',
          prop: 'statusText'
        },
        {
          label: '操作',
          prop: 'action',
          fixed: 'right',
          type: 'button',
          width: 150,
          buttons: [
            {
              label: '编辑',
              type: 'text',
              method: 'handleEdit',
              color: 'rgba(0, 118, 255, 1)',
              policy: ['system.accounts.edit']
            },
            {
              label: '删除',
              type: 'text',
              method: 'handleDelete',
              color: '#F37272',
              policy: ['system.accounts.remove']
            }
          ]
        }
      ],
      userDialogType: '',
      userDialogVisible: false,
      userDialogData: {
        workNumber: '',
        userName: '',
        phonenumber: '',
        password: '',
        belongSystem: '',
        deptId: '',
        deptName: '其它',
        status: '',
        oaStatus: '',
        roleIds: []
      },
      userDialogConfig: [
        {
          label: '帐号：',
          prop: 'workNumber',
          type: 'input',
          placeholder: '请输入人员帐号',
          rules: [
            { required: true, message: '请输入帐号', trigger: 'blur' },
            { max: 30, message: '帐号不能超过30个字符', trigger: 'blur' }
          ]
        },
        {
          label: '姓名：',
          prop: 'userName',
          type: 'input',
          placeholder: '请输入人员姓名',
          rules: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { max: 30, message: '姓名不能超过30个字符', trigger: 'blur' }
          ]
        },
        {
          label: '手机号：',
          prop: 'phonenumber',
          type: 'input',
          placeholder: '请输入手机号',
          rules: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
        },
        { label: '岗位：', prop: 'postName', type: 'input', placeholder: '请输入岗位' },
        // { label: '组织架构', prop: 'orgIds', type: 'cascader', multiple: true, emitPath: false },
        {
          label: '初始密码：',
          prop: 'password',
          type: 'input-password',
          placeholder: '初始默认Bg123456;限6~20个英文、数字,区分大小写',
          default: 'Bg123456'
        },
        {
          label: '组织架构：',
          prop: 'deptId',
          type: 'treeselect',
          placeholder: '其它',
          options: this.deptOptions,
          normalizer: this.normalizer
        },
        {
          label: '所属系统：',
          prop: 'belongSystem',
          type: 'select',
          options: [
            { label: 'CRM', value: '0' },
            { label: '劳保', value: '1' },
            { label: 'CRM和劳保', value: '2' }
          ],
          rules: [{ required: true, message: '请选择所属系统', trigger: 'change' }]
        },
        {
          label: 'OA状态：',
          prop: 'oaStatus',
          type: 'select',
          options: [
            { label: '试用', value: '0' },
            { label: '正式', value: '1' },
            { label: '临时', value: '2' },
            { label: '使用延期', value: '3' }
          ],
          rules: [{ required: true, message: '请选择OA状态', trigger: 'change' }]
        },
        {
          label: '状态：',
          prop: 'status',
          type: 'radio',
          options: [
            { label: '生效', value: '0' },
            { label: '失效', value: '1' },
            { label: '休眠', value: '2' }
          ],
          rules: [{ required: true, message: '请选择状态', trigger: 'change' }]
        }
      ],

      authDialogVisible: false,
      pages: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      }
    }
  },

  watch: {
    filterText(val) {
      if (this.$refs.orgTree) {
        this.$refs.orgTree.filter(val)
      }
    },
    'userDialogData.belongSystem': function (newSystem) {
      this.getRolesBySystem(newSystem)
    },
    deptOptions(newOptions) {
      this.userDialogConfig.find((item) => item.prop === 'deptId').options = newOptions
    }
  },
  async mounted() {
    // 编辑人员
    this.$bus.$on('handleEdit', async (rows) => {
      try {
        // 设置对话框类型和可见性
        this.userDialogType = '编辑'
        this.userDialogVisible = true
        // 获取用户详细信息，包括角色
        const response = await getUser(rows.userId)
        const user = response.data

        // 填充用户信息到对话框
        this.userDialogData = {
          userId: rows.userId,
          workNumber: rows.workNumber,
          userName: rows.userName,
          phonenumber: rows.phonenumber,
          password: 'Bg123456', // 可以初始化为空或其他默认值
          postName: rows.postName,
          deptName: rows.deptName,
          deptId: rows.deptId,
          belongSystem: rows.belongSystem,
          status: rows.status,
          oaStatus: rows.oaStatus,
          roleIds: rows.roleIds || []
        }
        // 获取系统对应的角色列表
        await this.getRolesBySystem(this.userDialogData.belongSystem)
        // 设置角色选择框的值
        this.selectValue = user.roleIds
        // 更新表单验证状态
        this.setPsdUsername()
      } catch (error) {
        this.$message.error('获取用户信息失败，请稍后再试！')
      }
    })
    // 删除人员
    this.$bus.$on('handleDelete', (rows) => {
      this.$confirm(`确认删除账号为" ${rows.userName} "的用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser(rows.userId).then((res) => {
          if (this.pages.total % this.pages.pageSize === 1) {
            const lastpage = (this.pages.total + this.pages.pageSize - 1) / this.pages.pageSize
            if (this.pages.pageNum == lastpage) {
              this.pages.pageNum = this.pages.pageNum - 1
            }
          }
          this.getTableData()
          this.$message({ type: 'success', message: '删除人员成功!' })
        })
      })
    })
  },
  beforeDestroy() {
    this.$bus.$off('handleEdit')
    this.$bus.$off('handleAuth')
    this.$bus.$off('handleDelete')
  },
  created() {
    this.getTableData()
    this.getDeptTreeSelect()
  },
  methods: {
    async getOtherDeptOptions() {
      try {
        const res = await deptOtherId()
        if (res.code === 200) {
          this.userDialogData.deptId = res.data
        } else {
          this.$message.error('获取其它组织架构失败')
        }
      } catch (error) {
        this.$message.error('接口请求失败，请稍后重试')
      }
    },
    getTransferTitles(belongSystem, selectedCount) {
      if (belongSystem === '0') {
        return ['CRM系统', `已选择${selectedCount}项`]
      } else if (belongSystem === '1') {
        return ['劳保系统', `已选择${selectedCount}项`]
      } else if (belongSystem === '2') {
        return ['CRM系统和劳保系统', `已选择${selectedCount}项`]
      }
      return ['可选角色', `已选择${selectedCount}项`]
    },
    handleTabClick(tab) {
      if (tab.name === 'authInfo') {
        this.userDialogWidth = '700px'
      } else {
        this.userDialogWidth = '470px'
      }
    },
    handleSearch() {
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleReset() {
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleSizeChange(v) {
      this.pages.pageSize = v
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleCurrentChange(v) {
      this.pages.pageNum = v
      this.getTableData()
    },
    handleUserDialog() {
      this.getDeptTreeSelect()
      this.getOtherDeptOptions()
      console.log(this.deptOptions)
      this.userDialogType = '新增'
      this.userDialogVisible = true
      this.activeTab = 'basicInfo'
      // 只初始化必要的字段
      this.userDialogData = {
        workNumber: '',
        userName: '',
        phonenumber: '',
        password: 'Bg123456',
        belongSystem: '',
        deptId: '',
        deptName: '其它',
        status: '0',
        oaStatus: '',
        roleIds: []
      }
      if (this.$refs.userEdit) {
        this.$refs.userEdit.resetFields()
      }
      this.roleOptions = []
      this.selectValue = []
      this.setPsdUsername()
    },
    handleUserDialogClose() {
      if (this.$refs.userForm) {
        this.$refs.userForm.resetFields()
      }
      this.roleOptions = []
      this.userDialogVisible = false
      this.selectValue = []
    },
    setPsdUsername() {
      const rule = [
        { required: true, trigger: 'change', message: '请输入密码' },
        { required: true, validator: this.passwordValid, trigger: 'change' }
      ]
      const isEdit = !!this.userDialogData.userId // 检查是否为编辑模式
      const psd = this.userDialogConfig.find((i) => i.prop === 'password')
      const deptId = this.userDialogConfig.find((i) => i.prop === 'deptId')
      if (!isEdit) {
        this.$set(psd, 'disabled', true)
        this.$set(this.userDialogData, 'password', 'Bg123456')
        this.$set(deptId, 'disabled', true)
        this.$set(this.userDialogData, 'deptId')
        this.$set(this.userDialogData, 'status', '0')
      } else {
        this.$set(psd, 'disabled', false)
        this.$set(deptId, 'disabled', false)
      }
    },
    handleAuthDialogClose() {},
    // 提交表单
    async handleUserSubmit() {
      try {
        // 先进行表单验证
        await this.$refs.userEdit.validate()
        const res = await deptOtherId()
        if (res && res.code === 200) {
          const deptOtherId = res.data

          // 将 deptOtherId 设置为 deptId
          const submitData = { ...this.userDialogData, deptId: deptOtherId }
          submitData.roleIds = [...this.selectValue]

          let response
          if (this.userDialogType === '新增') {
            response = await addUser(submitData)
            if (response.code != 200) {
              this.$message.error(response.msg)
              return
            }
            this.$message.success('用户新增成功！')
          }
          if (this.userDialogType === '编辑') {
            response = await updateUser(submitData)
            if (response.code != 200) {
              this.$message.error(response.msg)
              return
            }
            this.$message.success('用户编辑成功！')
          }
          this.handleUserDialogClose()
          this.getTableData()
        } else {
          this.$message.error('获取 deptOtherId 失败')
        }
      } catch (error) {
        // 表单验证失败或请求失败时，打印错误日志
        console.error('提交表单失败:', error)
      }
    },

    handleAuthSubmit() {},
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getTableData() {
      const params = {
        pageNum: this.pages.pageNum,
        pageSize: this.pages.pageSize,
        deptId: this.deptTree.id,
        ...this.queryParams
      }

      listUser(params)
        .then((res) => {
          this.tableData = res.rows.map((user) => {
            let statusText = ''
            if (user.status === '0') {
              statusText = '生效'
            } else if (user.status === '1') {
              statusText = '失效'
            } else if (user.status === '2') {
              statusText = '休眠'
            }
            const roleNames = user.roles
              .filter((role) => role.roleName)
              .map((role) => {
                let systemSuffix = ''
                if (user.belongSystem === '0') {
                  systemSuffix = ' (CRM)'
                } else if (user.belongSystem === '1') {
                  systemSuffix = ' (劳保)'
                } else if (user.belongSystem === '2') {
                  systemSuffix = ' (CRM和劳保)'
                }
                return role.roleName + systemSuffix
              })
              .join(', ')
            return {
              ...user,
              roleName: roleNames,
              statusText
            }
          })
          this.pages.total = res.total
        })
        .catch((error) => {
          // console.error('获取用户列表失败:', error)
        })
    },
    handleRoleCheck() {},
    // 获取角色数据并按belongSystem分组
    // async getRoleOptions() {
    //   const res = await roleOptionList()
    //   const roles = res.data
    //   // 处理后的数据
    //   const roleOptions = [
    //     {
    //       roleName: 'CRM',
    //       children: roles.filter((role) => role.belongSystem === '0')
    //     },
    //     {
    //       roleName: '劳保',
    //       children: roles.filter((role) => role.belongSystem === '1')
    //     }
    //   ]
    //   this.roleOptions = roleOptions
    // },
    // 获取系统对应的角色列表
    async getRolesBySystem(belongSystem) {
      if (!belongSystem) {
        return // 不发送请求
      }
      if (this.isFetchingRoles) return
      this.isFetchingRoles = true
      try {
        const response = await roleBySystem({ belongSystem })
        this.roleOptions = response.data.roles
        // 如果是编辑状态，确保选中的角色回显
        if (this.userDialogType === '编辑') {
          this.selectValue = this.userDialogData.roleIds
        }
      } catch (error) {
        // console.error('获取角色列表失败:', error);
      } finally {
        this.isFetchingRoles = false
      }
    },

    getDeptTreeSelect() {
      deptTreeSelect().then((res) => {
        this.deptTree = res.data
        this.deptOptions = res.data
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    async handleDeptTreeClick(node) {
      try {
        const deptId = node.id
        const params = {
          deptId,
          pageNum: this.pages.pageNum,
          pageSize: this.pages.pageSize,
          ...this.queryParams
        }
        const response = await listUser(params)
        this.tableData = response.rows
        this.pages.total = response.total
      } catch (error) {
        this.$message.error('获取用户列表失败，请稍后再试')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body .container {
  padding: 20px 0;
  .el-form-item {
    padding: 0;
  }
}
.table-container {
  display: flex;
  padding: 20px;
  .left {
    width: 300px;
    padding: 9px;
  }
  .right {
    flex: 1;
    .header {
      // padding: 20px;
    }
    .tabs {
    }

    .dialog-footer {
      display: flex;
      justify-content: right;
      .button {
        width: 100px;
      }
    }
    .roleTree {
      display: flex;
    }
    .m_96 {
      margin: 20px 0;
    }
  }
  ::v-deep .el-form-item {
    display: flex;
    align-items: center;
    .el-form-item__label {
      text-align: right;
      width: 82px;
      height: 22px;
      &:after {
        // content: '*';
        color: #f56c6c;
        position: relative !important;
        left: -5px;
        top: 0px;
        margin-left: 5px;
      }
    }
  }
}
</style>
